package org.fly.service.impl;

import org.fly.bean.SmsTemplate;
import org.fly.bean.query.SmsTemplateQuery;
import org.fly.contants.ErrorConstant;
import org.fly.dao.SmsTemplateDao;
import org.fly.service.SmsTemplateService;
import org.fly.utils.UUIDFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.fly.bean.common.BusinessException;
import java.util.List;

/**
* Created by autoCode on 2018-05-02 17:04:48.
*/
@Service
public class SmsTemplateServiceImpl implements SmsTemplateService {

    @Autowired
    SmsTemplateDao smsTemplateDao;

    @Override
    public List<SmsTemplate> list(SmsTemplateQuery query) {
        return smsTemplateDao.list(query);
    }

    @Override
    public long count(SmsTemplateQuery query) {
        return smsTemplateDao.count(query);
    }

    @Override
    public SmsTemplate findById(String id) {
        return smsTemplateDao.findById(id);
    }

    @Override
    public void save(SmsTemplate bean)  throws BusinessException {
        SmsTemplate db  = smsTemplateDao.findByType(bean.getType());
        if(db !=null && !bean.getId().equals(db.getId())){
            throw new BusinessException(ErrorConstant.ec_pk_error,ErrorConstant.em_pk_error);
        }
        if(StringUtils.isNotBlank(bean.getId())){
             smsTemplateDao.update(bean);
        }else {
            bean.setId(UUIDFactory.random());
            bean.setCreateTime(System.currentTimeMillis());
            smsTemplateDao.insert(bean);
        }
    }

    @Override
    public void delete(String id) {
        smsTemplateDao.delete(id);
    }

    @Override
    public SmsTemplate findByType(String type) {
        return smsTemplateDao.findByType(type);
    }
}
